<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="12">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="appropriationName"
                  label-width="180px"
                  label="经费科目名称："
                >
                  <el-input
                    :disabled="isProcess ||isCost"
                    v-model="postForm.appropriationName"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请输入经费科目名称"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="预算标准（单位：千）："
                  prop="appropriationStandard"
                >
                  <el-input
                    :disabled="isProcess ||isCost"
                    v-model="postForm.appropriationStandard"
                    class="article-textarea"
                    autosize
                    placeholder="请输入整数设定预算标准"
                    required
                  />
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="经费科目说明："
                >
                  <el-input
                    :disabled="isProcess ||isCost"
                    v-model="postForm.appropriationDescription"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入经费科目说明"
                  />
                </el-form-item>
              </el-row>
            </div>
          </el-col>

          <el-col :span="12">
            <el-row>
              <el-form-item
                label-width="120px"
                label="起始年度："
                class="postInfo-container-item"
                prop="appropriationStart"
              >
                <el-date-picker
                  :disabled="isProcess ||isCost"
                  v-model="displayAppropriationStart"
                  type="year"
                  value-format="yyyy"
                  placeholder="选择起始年度"
                  required
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                label-width="120px"
                label="结束年度："
                class="postInfo-container-item"
                prop="appropriationEnd"
              >
                <el-date-picker
                  :disabled="isProcess ||isCost"
                  v-model="displayAppropriationEnd"
                  type="year"
                  value-format="yyyy"
                  placeholder="选择结束年度"
                  required
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                label-width="120px"
                class="postInfo-container-item"
                prop="appropriationState"
                label="经费科目状态："
                >
                  <el-input
                    v-model="postForm.appropriationState"
                    name="appropriationState"
                    size="small"
                    type="text"
                    :disabled="true"
                  >
                  </el-input>
                </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <div style="margin-left: 230px">
        <el-button
          v-show="!isView && !isProcess && !isCost"
          v-loading="loading"
          style="width: 100px"
          type="success"
          @click="submitForm"
        >
         保存
        </el-button>
        <el-button v-if="isProcess || isCost" @click="approveAppropriation(false)"
        >驳回</el-button>
        <el-button
          v-if="isProcess"
          v-loading="loading"
          style="margin-left: 230px; width: 130px"
          type="success"
          @click="approveAppropriation(true)"
        >
          通过领导审批
        </el-button>
        <el-button
          v-if="isCost"
          v-loading="loading"
          style="margin-left: 230px; width: 130px"
          type="success"
          @click="approveAppropriation(true)"
        >
          通过财务审批
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  fetchAppropriationById,
  createAppropriation,
  updateAppropriation,
} from "@/api/appropriation";
import { mapGetters } from "vuex";

const defaultForm = {
  appropriationName: "", // 经费科目名称
  appropriationDescription: "", // 经费科目说明
  appropriationStandard: 0, // 预算标准
  appropriationState: "待生效", // 经费科目状态：待生效，待领导审批，领导审批驳回，待财务审批，财务审批驳回 已生效
  appropriationStart: "", // 经费科目起始年度
  appropriationEnd: "", // 经费科目结束年度
  appropriationCreatorId: "", // 经费科目创建者
  appropriationApproveDate: null,
  appropriationCostApproverId: null,
  appropriationCostApproverName: '',
  appropriationCostApproveComment: '',
  appropriationPreApproverId: null,
  appropriationPreApproverName: '',
  appropriationPreApproveComment: '',
  id: undefined,
};

export default {
  name: "AppropriationDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
    isProcess: {
      type: Boolean,
      default: false,
    },
    isCost: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    const validateTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        if (value < this.postForm.appropriationStart) {
          callback(new Error("结束年度应大于起始年度"));
        } else {
          callback();
        }
      }
    };

    const validateCost = (rule, value, callback) => {
      const separator = '.';
      const regexPart = '*';
      const validationRegex = new RegExp(`^[-+]?\\d*(\\${separator}\\d${regexPart})?([eE]{1}[-]?\\d+)?$`);
      if (!value || value === "" || value <= 0) {
        callback(new Error("请输入预算标准"));
      } else if (value.toString().match(validationRegex)) {
        callback();
      } else {
        callback(new Error("请输入数字"));
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        appropriationName: [{ required: true, validator: validateRequire }],
        appropriationStandard: [
          { required: true, validator: validateCost }
        ],
        appropriationStart: [{ required: true, validator: validateRequire }],
        appropriationEnd: [{ required: true, validator: validateTime }],
      },
    };
  },
  computed: {
    ...mapGetters(["id", "name", "roles"]),
    descriptionLength() {
      return this.postForm.appropriationDescription.length;
    },
    displayAppropriationStart: {
      get() {
        return this.postForm.appropriationStart.toString();
      },
      set(val) {
        this.postForm.appropriationStart = new Date(val).getFullYear();
      },
    },
    displayAppropriationEnd: {
      get() {
        return this.postForm.appropriationEnd.toString();
      },
      set(val) {
        this.postForm.appropriationEnd = new Date(val).getFullYear();
      },
    },
  },
  created() {
    if (this.isEdit || this.isView || this.isProcess || this.isCost) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  methods: {
    fetchData(id) {
        fetchAppropriationById(id)
        .then((res) => {
          this.postForm = res.data[0];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    approveAppropriation(isApprove) {
      if (isApprove) {
        if (this.isProcess) {
          this.postForm.appropriationState = "待财务审批";
          this.postForm.appropriationPreApproverId = this.id;
          this.postForm.appropriationPreApproverName = this.name;
        } else {
          this.postForm.appropriationState = "已生效";
          this.postForm.appropriationCostApproverId = this.id;
          this.postForm.appropriationCostApproverName = this.name;
        }
      } else {
        if (this.isProcess) {
          this.postForm.appropriationState = "领导审批驳回";
          this.postForm.appropriationPreApproverId = this.id;
          this.postForm.appropriationPreApproverName = this.name;
        } else {
          this.postForm.appropriationState = "财务审批驳回";
          this.postForm.appropriationCostApproverId = this.id;
          this.postForm.appropriationCostApproverName = this.name;
        }
      }
      this.postForm.appropriationApproveDate = Date.now();
      this.submitForm();
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          if (this.postForm.id) {
            updateAppropriation(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/appropriation/list");
                  this.$message({
                    title: "成功",
                    message: "经费科目更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "经费科目更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            this.postForm.appropriationCreatorId = this.id;
            createAppropriation(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/appropriation/list");

                  this.$message({
                    title: "成功",
                    message: "经费科目创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "经费科目创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("经费科目保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
